#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    // 判断用户输入
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    // 获取用户输入数据
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    // 创建服务器信息字段，并填写
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));

    while (1)
    {
        int cnt = 5;
        bool isconnect = false;
        // 创建套接字
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std ::cerr << "socket error" << std::endl;
            return 1;
        }

        do
        {
            
            // 连接
            if (connect(sockfd, (const struct sockaddr *)(&server), sizeof(server)) < 0)
            {
                isconnect = true;
                cnt--;
                std::cout << "user ofline...,reconnet" << cnt << std::endl;
                sleep(2);
            }
            else
            {
                break;
            }
        } while (cnt && isconnect);

        if(cnt == 0)
        {
            std::cout << "user ofline..."<< std::endl;
            break; 
        }

        // 发送数据
        std::string message;
        std::cout << "please enter#" << std::endl;
        std::getline(std::cin, message);

        int ret = write(sockfd, message.c_str(), message.size());
        if (ret < 0)
        {
            printf("write error, errno : %d , errstr : %s", errno, strerror(errno));
            //break;
        }

        char inbuffer[4096];
        int n = read(sockfd, inbuffer, sizeof(inbuffer));
        if (n > 0)
        {
            inbuffer[n] = 0;
            std::cout << inbuffer << std::endl;
        }
        else
        { 
            //break;
        }

        close(sockfd);
    }
    return 0;
}